package com.wjf.common.interceptor;

import com.wjf.common.utils.ThreadLocalUtils;
import com.wjf.common.utils.JwtUtils;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;

import java.util.Map;

@Component
public class UserInfoInterceptor implements HandlerInterceptor {
    
    private static final Logger log = LoggerFactory.getLogger(UserInfoInterceptor.class);
    
    @Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
    String token = request.getHeader("token");
    
    // 检查token是否为空
    if (token == null || token.isEmpty()) {
        log.warn("未提供token");
        response.setStatus(HttpStatus.UNAUTHORIZED.value());
        return false;
    }
    
    // 解析token获取claims
    try {
        Map<String, Object> claims = JwtUtils.parseToken(token);
        if (claims == null) {
            log.warn("token解析失败");
            response.setStatus(HttpStatus.UNAUTHORIZED.value());
            return false;
        }

        // 存入ThreadLocal之前先清理
        ThreadLocalUtils.remove();
        
        // 直接存储整个claims对象，不进行类型转换
        ThreadLocalUtils.set("claims", claims);
        
        // 记录日志时使用toString()方法
        log.info("ThreadLocal中的数据: {}", claims.toString());
        return true;
    } catch (Exception e) {
        log.error("token处理异常", e);
        response.setStatus(HttpStatus.UNAUTHORIZED.value());
        return false;
    }
}

@Override
public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) {
    ThreadLocalUtils.remove();
    log.info("ThreadLocal已清理");
}
} 